<?php
/**
 * GioCMS
 * 
 * LICENSE
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE Version 2 
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-2.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@ninhgio.com so we can send you a copy immediately.
 * 
 * @copyright	Copyright (c) 2010-2011 GioCMS (http://cms.ninhgio.com)
 * @license		http://www.gnu.org/licenses/gpl-2.0.txt GNU GENERAL PUBLIC LICENSE Version 2
 * @author		NinhGio - ninhgio@gmail.com
 * @since		1.0
 */

class Modules_Core_Services_Installer
{
	public static function validate($configs)
	{
		$data = array();
		$validator = new Gio_Core_Validator();
				
		$data['messages']['server_static'] = $validator->setString($configs['server']['static'])
												->validate(array('notNull')
																, array(
																	'notNull' => 'install_server_static_notnull',
																)
														);
														
		$data['messages']['server_resource'] = $validator->setString($configs['server']['resource'])
												->validate(array('notNull')
																, array(
																	'notNull' => 'install_server_resource_notnull',
																)
														);
														
		$data['messages']['web_name'] = $validator->setString($configs['web']['name'])
												->validate(array('notNull')
																, array(
																	'notNull' => 'install_web_name_notnull',
																)
														);
														
		$data['messages']['web_template'] = $validator->setString($configs['web']['template'])
												->validate(array('notNull')
																, array(
																	'notNull' => 'install_web_template_notnull',
																)
														);
														
		$data['messages']['web_skin'] = $validator->setString($configs['web']['skin'])
												->validate(array('notNull')
																, array(
																	'notNull' => 'install_web_skin_notnull',
																)
														);
														
		$data['messages']['web_admin_url_prefix'] = $validator->setString($configs['web']['admin']['url_prefix'])
												->validate(array('notNull', 'isCharacter')
																, array(
																	'notNull' => 'install_web_admin_url_prefix_notnull',
																	'isCharacter' => 'install_web_admin_url_prefix_invalid',
																)
														);

		$configs['db']['name'] = isset($configs['db']['name']) ? $configs['db']['name'] : null;
		$data['messages']['db_name'] = $validator->setString($configs['db']['name'])
												->validate(array('notNull')
																, array(
																	'notNull' => 'install_db_name_notnull',
																)
														);
														
		$data['messages']['db_table_prefix'] = $validator->setString($configs['db']['table_prefix'])
												->validate(array('notNull', 'isCharacter')
																, array(
																	'notNull' => 'install_db_table_prefix_notnull',
																	'isCharacter' => 'install_db_table_prefix_invalid',
																)
														);
												
		$error = false;
		foreach ($data['messages'] as $index => $message) {
			if ($message) {
				$data['messages_error'] = true;
				return $data;
			}
		}										
		$data['messages_error'] = false;
		return $data; 
	}
	
	/**
	 * Perform install actions
	 * 
	 * @param bool $importSampleData
	 * @return bool
	 */
	public static function install($importSampleData = false, $adminInfo = array())
	{
		try {
			$view = Gio_Core_View::getInstance();
			$moduleDirs = Gio_Core_File::getSubDir(ROOT_DIR . DS . 'modules');
			
			/**
			 * Install modules
			 */
			$modules = array();
			foreach ($moduleDirs as $module) {
				$modules[] = Modules_Core_Services_Module::install($module);
			}
			
			foreach ($modules as $module) {
				if ($module) {
					Modules_Core_Services_Module::add($module);
				}
			}
			
			/**
			 * Install widgets
			 */
			foreach ($moduleDirs as $module) {
				/**
				 * Load all widgets from module
				 */
				$widgetDirs = Gio_Core_File::getSubDir(ROOT_DIR . DS . 'modules' . DS . $module . DS . 'widgets');
				foreach ($widgetDirs as $widgetName) {
					$widget = array(
						'module_id' 	=> $module,
						'widget_id' 	=> $widgetName,
						'title' 		=> $view->TRANSLATOR->widget('about_title', $module, $widgetName),
						'description'	=> $view->TRANSLATOR->widget('about_description', $module, $widgetName),
						'created_date'	=> date('Y-m-d H:i:s')
					);
					Modules_Core_Services_Widget::add($widget);
				}
			}
			
			/**
			 * Create resources and previleges
			 */
			foreach ($moduleDirs as $module) {
				$file = ROOT_DIR . DS . 'modules' . DS . $module . DS . 'configs' . DS . 'permissions.xml';
				if (!file_exists($file)) {
					continue;
				}
				$xml = simplexml_load_file($file);
				foreach ($xml->controller as $res) {
					$attr        = $res->attributes();
					$langKey     = (string) $attr['langKey'];
					$description = $view->TRANSLATOR->translator($langKey, $module);
					$description = ($description == $langKey) ? (string) $attr['description'] : $description;
					
					$resource    = array(
									'controller_id'	=> $attr['name'],
									'description'	=> $description,
									'module_id'	  	=> $module,
									'created_date'	=> date('Y-m-d H:i:s')
								);
					/**
					 * Add resource
					 */
					Modules_Core_Services_Controller::add($resource);
					
					if ($res->action) {
						foreach ($res->action as $pri) {
							$attr2       = $pri->attributes();
							$langKey     = (string) $attr2['langKey'];
							$description = $view->TRANSLATOR->translator($langKey, $module);
							$description = ($description == $langKey) ? (string) $attr2['description'] : $description;
							
							$privilege = array(
										'controller_id'	=> $attr['name'],
										'description'	=> $description,
										'module_id'	  	=> $module,
										'action_id'	  	=> $attr2['name'],
										'created_date'	=> date('Y-m-d H:i:s')
									);
							Modules_Core_Services_Action::add($privilege);
						}
					}
				}
			}
			
			/**
			 * Finally, init data
			 */
			$dbFile    = ROOT_DIR . DS . 'install' . DS . 'db.xml';
			if (file_exists($dbFile)) {
				$xml   = simplexml_load_file($dbFile);
				$xpath = $xml->xpath('module/query');
				if (is_array($xpath) && count($xpath) > 0) {
					$conn = Gio_Db_Connection::getConnection();
					foreach ($xpath as $query) {
						$q = str_replace('###table_prefix###', $conn->_tablePrefix, (string) $query);
						$conn->query($q);
					}
				}
			}
			
			/**
			 * Allows user to import sample data
			 */
			if ($importSampleData) {
				$file 	  = ROOT_DIR . DS . 'install' . DS . 'giocms_sample_db.sql';
				$importer = Gio_Core_Import_Importer::getInstance();
				if ($importer != null && $file != null) {
					$importer->import($file);
				}
			}
			
			/**
			 * Create admin user
			 */
			$salt = md5(time());
			$user = array(
					'username' 	   => $adminInfo['username'],
					'password' 	   => md5(md5($adminInfo['password']) . $salt),
					'email'		   => $adminInfo['email'],					
					'fullname' 	   => $adminInfo['fullname'],
					'salt'		   => $salt, 
					'status'	   => 'active',
					'created_date' => date('Y-m-d H:i:s'),
					'role_id'	   => 1
			);
			Modules_Core_Services_User::add($user);
			
		} catch (Exception $ex) {
			return false;
		}
		
		return true;
	}
}